import CryptoJS from 'crypto-js'
import btoa from 'btoa'
// import pinyin from 'pinyin'
//set 对象内容
export const setValue = (name, data) => {
    sessionStorage.setItem("" + name, JSON.stringify(data))
}

//get 取内容
export const getValue = (name) => {
    const value = sessionStorage.getItem("" + name)
    if (value) {
        let info = JSON.parse(value)
        return info
    } else return false
}

// mp加密
export const encryptOne = (pwd, keyStr, ivStr) => {
    var key = CryptoJS.enc.Utf8.parse(keyStr);
    var iv = CryptoJS.enc.Utf8.parse(ivStr)

    const timestap = new Date().getTime();
    const curhour = parseInt((timestap / 1000 - 1514736000) / 3600); //1527782400
    // const curhour = '13656'

    var bytes = new Array();
    bytes = pwd;
    var bytenew = new Array();
    bytenew[0] = intToByte(curhour & 255);
    bytenew[1] = intToByte((curhour & 65280) >> 8);
    bytenew[2] = intToByte((curhour & 16711680) >> 16);
    bytenew[3] = intToByte((curhour & 255) >> 24);
    for (var i = 0; i < bytes.length; i++) {
        bytenew[i + 4] = bytes[i];
    }
    pwd = binary2base64(bytenew);
    pwd = CryptoJS.enc.Base64.parse(pwd)
    var enc = CryptoJS.AES.encrypt(pwd, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })
    var enced = enc.toString();
    return enced;
}


// aes 加密
export const encrypt = (pwd, keyStr, ivStr) => {
    var key = CryptoJS.enc.Utf8.parse(keyStr);
    var iv = CryptoJS.enc.Utf8.parse(ivStr)

    const timestap = new Date().getTime();
    const curhour = parseInt((timestap / 1000 - 1514736000) / 3600); //1527782400
    // const curhour = '13656'

    var bytes = new Array();
    bytes = pwd;
    var bytenew = new Array();
    bytenew[0] = intToByte(curhour & 255);
    bytenew[1] = intToByte((curhour & 65280) >> 8);
    bytenew[2] = intToByte((curhour & 16711680) >> 16);
    bytenew[3] = intToByte((curhour & 255) >> 24);
    for (var i = 0; i < bytes.length; i++) {
        bytenew[i + 4] = bytes[i];
    }
    pwd = binary2base64(bytenew);
    pwd = CryptoJS.enc.Base64.parse(pwd)
    var enc = CryptoJS.AES.encrypt(pwd, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })
    var enced = enc.toString();
    return enced;
}

// 是否要转成string

// aes解密
export const decrypt = (cipherText, keyStr, ivStr) => {

    var key = CryptoJS.enc.Utf8.parse(keyStr)
    var iv = CryptoJS.enc.Utf8.parse(ivStr)
        // var cipherTextHexStr = CryptoJS.enc.Hex.parse(cipherText)

    // 将密文转为Base64的字符串
    // 只有Base64类型的字符串密文才能对其进行解密
    //  var cipherTextBase64Str = CryptoJS.enc.Base64.stringify(cipherTextHexStr)

    // const timestap = new Date().getTime();
    // const curhour = parseInt((timestap / 1000 - 1527782400) / 3600); //1527782400
    var dec = CryptoJS.AES.decrypt(cipherText, key, {
        iv: iv,
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC
    });
    var byteArray = wordToByteArray(dec.words);
    byteArray = byteArray.slice(4, dec.sigBytes);



    return decodeURIComponent(byteArrayToString(byteArray))
}

export const decryptone = (cipherText, keyStr, ivStr) => {

    var key = CryptoJS.enc.Utf8.parse(keyStr)
    var iv = CryptoJS.enc.Utf8.parse(ivStr)
        // var cipherTextHexStr = CryptoJS.enc.Hex.parse(cipherText)

    var wordArray = int8parse(cipherText);
    var base64Str = CryptoJS.enc.Base64.stringify(wordArray);

    var dec = CryptoJS.AES.decrypt(base64Str, key, {
        iv: iv,
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC
    });

    var byteArray = wordToByteArray(dec.words);
    byteArray = byteArray.slice(4, dec.sigBytes);


    return byteArray
}


export const stringToByte = (str) => {
    var bytes = new Array();
    var len, c;
    len = str.length;
    for (var i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if (c >= 0x010000 && c <= 0x10FFFF) {
            bytes.push(((c >> 18) & 0x07) | 0xF0);
            bytes.push(((c >> 12) & 0x3F) | 0x80);
            bytes.push(((c >> 6) & 0x3F) | 0x80);
            bytes.push((c & 0x3F) | 0x80);
        } else if (c >= 0x000800 && c <= 0x00FFFF) {
            bytes.push(((c >> 12) & 0x0F) | 0xE0);
            bytes.push(((c >> 6) & 0x3F) | 0x80);
            bytes.push((c & 0x3F) | 0x80);
        } else if (c >= 0x000080 && c <= 0x0007FF) {
            bytes.push(((c >> 6) & 0x1F) | 0xC0);
            bytes.push((c & 0x3F) | 0x80);
        } else {
            bytes.push(c & 0xFF);
        }
    }
    return bytes;
}

export const byteToString = (arr) => {
    if (typeof arr === 'string') {
        return arr;
    }
    var str = '',
        _arr = arr;
    for (var i = 0; i < _arr.length; i++) {
        var one = _arr[i].toString(2),
            v = one.match(/^1+?(?=0)/);
        if (v && one.length == 8) {
            var bytesLength = v[0].length;
            var store = _arr[i].toString(2).slice(7 - bytesLength);
            for (var st = 1; st < bytesLength; st++) {
                store += _arr[st + i].toString(2).slice(2);
            }
            str += String.fromCharCode(parseInt(store, 2));
            i += bytesLength - 1;
        } else {
            str += String.fromCharCode(_arr[i]);
        }
    }
    return str;
}

export const intToByte = (i) => {
    var b = i & 0xFF;
    var c = 0;
    if (b >= 128) {
        c = b % 128;
        c = -1 * (128 - c);
    } else {
        c = b;
    }
    return c;
}

export const HexString2Bytes = (str) => {
    var pos = 0;
    var len = str.length;
    if (len % 2 != 0) {
        return null;
    }
    len /= 2;
    var arrBytes = new Array();
    for (var i = 0; i < len; i++) {
        var s = str.substr(pos, 2);
        var v = parseInt(s, 16);
        arrBytes.push(v);
        pos += 2;
    }
    return arrBytes;
}

export const wordToByteArray = (wordArray) => {
    var byteArray = [],
        word, i, j;
    for (i = 0; i < wordArray.length; ++i) {
        word = wordArray[i];
        for (j = 3; j >= 0; --j) {
            byteArray.push((word >> 8 * j) & 0xFF);
        }
    }
    return byteArray;
}

export const byteArrayToString = (byteArray) => {
    var str = "",
        i;
    for (i = 0; i < byteArray.length; ++i) {
        str += escape(String.fromCharCode(byteArray[i]));
    }
    return str;
}


// 切割揭秘回来的token取值
export const cuttingValue = (str) => {
    let arr = str.split('|')
    let obj = {
        pwd: arr[0],
        key: arr[1].substring(0, 16)
    }
    return obj
}

export const int8parse = (u8arr) => {
    var len = u8arr.length;
    var words = [];
    for (var i = 0; i < len; i++) {
        words[i >>> 2] |= (u8arr[i] & 0xff) << (24 - (i % 4) * 8);
    }
    return CryptoJS.lib.WordArray.create(words, len);
}

export const binary2base64 = (bytes) => {
    var bString = "";
    for (var i = 0, len = bytes.length; i < len; ++i) {
        bString += String.fromCharCode(bytes[i]);
    }
    return btoa(bString);
}

/**
 * 图片按宽高比例进行自动缩放
 * @param ImgObj
 *      缩放图片源对象
 * @param maxWidth
 *      允许缩放的最大宽度
 * @param maxHeight
 *      允许缩放的最大高度
 */
export const drawImage = (ImgObj, maxWidth, maxHeight) => {
    var image = ImgObj
    // 用于设定图片的宽度高度
    var tempWidth, tempHeight
    if(image.width > 0 && image.height > 0){
        // 原图片宽高比例 大于  指定宽高比例，这就说明了原图片的宽度必然 > 高度
        if(image.width / image.height >= maxWidth / maxHeight){
            if(image.width > maxWidth){
                tempWidth = maxWidth
                //按原图片的比例进行缩放
                tempHeight = (image.height * maxHeight) / image.width
            }else{
                //按原图片大小进行缩放
                tempHeight = image.height
                tempWidth = image.width
            }
        }else{//原图片高度必然 > 宽度
            if(image.height > maxHeight){
                tempHeight = maxHeight
                tempWidth = (image.width*maxHeight) / image.height
            }else{
                //按原图片大小进行缩放
                tempHeight = image.height
                tempWidth = image.width
            }
        }
    }
    return {tempHeight:tempHeight,tempWidth:tempWidth}
}

export const base64ToArrayBuffer = (base64) => {
    var arr = base64.split(',')
    var binaryString = window.atob(arr[1])
    var len = binaryString.length
    var bytes = new Uint8Array(len)
    for (var i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i)
    }
    return bytes
}

// 缩略图
export const resizeImage = (url,callback,maxWidth,maxHeight) => {
    var canvas = document.createElement('canvas'); //创建一个canvas
    var ctx = canvas.getContext('2d'); //返回一个用于在画布上绘图的2维环境
    var image = new Image()
    image.setAttribute('crossOrigin', 'Anonymous')
    image.src = url
    image.onload = function(){
        if(image.width > 0 && image.height > 0){
            // 原图片宽高比例 大于  指定宽高比例，这就说明了原图片的宽度必然 > 高度
            if(image.width / image.height >= maxWidth / maxHeight){
                if(image.width > maxWidth){
                    //按原图片的比例进行缩放
                    canvas.width = maxWidth
                    canvas.height = (image.height * maxHeight) / image.width
                    ctx.drawImage(image,0,0,maxWidth,(image.height * maxHeight) / image.width)
                    
                }else{
                    //按原图片大小进行缩放
                    canvas.width = image.width
                    canvas.height =  image.height
                    ctx.drawImage(image,0,0,image.width,image.height)
                }
            }else{//原图片高度必然 > 宽度
                if(image.height > maxHeight){
                    canvas.width = (image.width*maxHeight) / image.height
                    canvas.height =  maxHeight
                    ctx.drawImage(image,0,0,(image.width*maxHeight) / image.height,maxHeight)
                }else{
                    //按原图片大小进行缩放
                    canvas.width = image.width
                    canvas.height =  image.height
                    ctx.drawImage(image,0,0,image.width,image.height)
                }
            }
        }
        callback(base64ToArrayBuffer(canvas.toDataURL("image/png")))
    }
}

export const arrayBufferToBase64 = ( buffer ) => {
        var binary = '';
        var bytes = new Uint8Array( buffer );
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode( bytes[ i ] );
        }
        return "data:image/png;base64," + window.btoa( binary );
}